<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 检测权限是否存在 url
 * adminer 私有
 * @param  string $url 路径
 * @return boolean
 */
function get_purview($url){

	if (!$url) {
		return false;
	}

	$CI =& get_instance();

	if (!$CI->session->userdata('gid')) {
		return false;
	}

	if ($CI->session->userdata('gid') == 1) {
		return TRUE;
	}

	$pur = md5($url);
	// 过滤disable不保护的权限
	$uris_disable = $CI->mpur->get_disable_list();
	if (in_array($pur,$uris_disable)) {
		return TRUE;
	}

	$group = $CI->mmger->get_group($CI->session->userdata('gid'));
	if (in_array($pur, explode(',', $group['purview']))) {
		return TRUE;
	}
	if ($CI->session->userdata('gid') == 1) {
		return TRUE;
	}
	return false;
}

/*
 * 文件删除
 * 同时删除 boc_upload 中的记录
 * $fids 为 boc_upload 的标识，接受 array()
 */
function unlink_upload($fids=false)
{

	$CI =& get_instance();
	// 注意控制器是否加载了 mupload
	if (!isset($CI->mupload)) {
		$CI->load->model('Upload_model','mupload');
	}

	if (is_array($fids)) {

		$tmp = array();
		foreach ($fids as $v) {
			array_push($tmp, intval($v));
		}
		$fids = $tmp;
		$ps = $CI->mupload->get_in($fids);
		foreach ($ps as $v) {
			$f = urldecode($v['url']);
			$ft = urldecode($v['thumb']);
			if (is_file(UPLOAD_PATH.$f)) {
				unlink(UPLOAD_PATH.$f);
			}
			if (is_file(UPLOAD_PATH.$ft)) {
				unlink(UPLOAD_PATH.$ft);
			}
		}
		$CI->mupload->del($fids,true);
		return TRUE;
	}
	return FALSE;
}

/**
 * 栏目ids
 * @param  [type] $ids [description]
 * @return [type]      [description]
 */
function list_uploads_ids($ids){

}
function get_ctype_title($ctype) {
	$CI =& get_instance();
	if (!isset($CI->mcoltypes)) {
		$CI->load->model('coltypes_model','mcoltypes');
	}
	return $CI->mcoltypes->get_one($ctype,'title');
}
function get_ctype_titles($ctype) {
	$ids = explode(',',$ctype);
	$CI =& get_instance();
	if (!isset($CI->mcoltypes)) {
		$CI->load->model('category_model','mcategory');
	}
	$titles = $CI->mcategory->get_all(array('in'=>array('id',$ids)),'title');
	$title = array();
	foreach($titles as $row) {
		$title[] = $row['title'];
	}
	return implode(' | ',$title);
}
function get_account_name($uid) {
	$CI =& get_instance();
	if (!isset($CI->mcoltypes)) {
		$CI->load->model('account_model','maccount');
	}
	$account = $CI->maccount->get_one($uid,'uname,phone');
	return $account['uname'].'（'.$account['phone'].'）';
}
function get_first_string($str) {
	$industry = '';
	$str = explode('_',$str);
	foreach($str as $row) {
		$industry .=substr($row,0,1);
	}
	return $industry;
}
function get_tags_title($ctype,$info,$is_success = 1) {
	$CI =& get_instance();
	if (!isset($CI->mcategory)) {
		$CI->load->model('category_model','mcategory');
	}
	if (!isset($CI->mcoltypes)) {
		$CI->load->model('coltypes_model','mcoltypes');
	}
	switch($ctype) {
		case 1:
			$cids = array(24,25);
			$data = array('industry'=>$info['industry'],'tags'=>$info['tags']);
			$info_title = $CI->mcoltypes->get_all(array('in'=>array('id',$cids)),'id,title');
			$info_title1 = array();
			foreach($info_title as $v) {
				$info_title1[$v['id']] = $v['title'];
			}
			$industry = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['industry'])))),'title');
			$title = array();
			$info['exts'][0]['key'] = $info_title1[$cids[0]];
			foreach($industry as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][0]['value'] = $title ? implode(',',$title) : '';
			unset($title);
			$info['exts'][1]['key'] = $info_title1[$cids[1]];
			$tags = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['tags'])))),'title');
			foreach($tags as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][1]['value'] = isset($title) ? implode(',',$title) : '';

			break;
		case 2:
			$cids = array(24,26,27);
			$data = array('interested' => $info['interested'],'fund_stage'=>$info['fund_stage'],'single_project'=>$info['single_project']);
			$info_title = $CI->mcoltypes->get_all(array('in'=>array('id',$cids)),'id,title');
			$info_title1 = array();
			foreach($info_title as $v) {
				$info_title1[$v['id']] = $v['title'];
			}
			$interested = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['interested'])))),'title');
			$title = array();
			$info['exts'][0]['key'] = $info_title1[$cids[0]];
			foreach($interested as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][0]['value'] = $title ? implode(',',$title) : '';
			unset($title);
			$info['exts'][1]['key'] = $info_title1[$cids[1]];
			$fund_stage = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['fund_stage'])))),'title');
			foreach($fund_stage as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][1]['value'] = isset($title) ? implode(',',$title) : '';
			unset($title);
			$info['exts'][2]['key'] = $info_title1[$cids[2]];
			$single_project = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['single_project'])))),'title');
			foreach($single_project as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][2]['value'] = isset($title) ? implode(',',$title) : '';
			break;
		case 3:
			$cids = array(24,24);
			$data = array('industry'=>$info['industry'],'interested' => $info['interested']);
			$info_title = $CI->mcoltypes->get_all(array('in'=>array('id',$cids)),'id,title');
			$info_title1 = array();
			foreach($info_title as $v) {
				$info_title1[$v['id']] = $v['title'];
			}
			$info['exts'][0]['key'] = $info_title1[$cids[0]];
			$industry = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['industry'])))),'title');
			$title = array();
			foreach($industry as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][0]['value'] = $title ? implode(',',$title) : '';
			unset($title);
			$info['exts'][1]['key'] = '感兴趣行业';
			$interested = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['interested'])))),'title');
			foreach($interested as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][1]['value'] = isset($title) ? implode(',',$title) : '';
			break;
		case 4:
			$cids = array(24,24);
			$data = array('good_industry' => $info['good_industry'],'interested' => $info['interested']);
			$info_title = $CI->mcoltypes->get_all(array('in'=>array('id',$cids)),'id,title');
			$info_title1 = array();
			foreach($info_title as $v) {
				$info_title1[$v['id']] = $v['title'];
			}
			$info['exts'][0]['key'] = '最擅长的行业';
			$good_industry = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['good_industry'])))),'title');
			$title = array();
			foreach($good_industry as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][0]['value'] = $title ? implode(',',$title) : '';
			unset($title);
			$info['exts'][1]['key'] = '感兴趣行业';
			$interested = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['interested'])))),'title');
			$title = array();
			foreach($interested as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][1]['value'] = isset($title) ? implode(',',$title) : '';
			break;
		case 5:
			$cids = array(24);
			$data = array('interested' => $info['interested']);
			$interested = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['interested'])))),'title');
			$title = array();
			$info['exts'][0]['key'] = '感兴趣行业';
			foreach($interested as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][0]['value'] = $title ? implode(',',$title) : '';
			break;
		case 6:
			$cids = array(28,24);
			$data = array('business_type'=>$info['business_type'],'interested' => $info['interested']);
			$info_title = $CI->mcoltypes->get_all(array('in'=>array('id',$cids)),'id,title');
			$info_title1 = array();
			foreach($info_title as $v) {
				$info_title1[$v['id']] = $v['title'];
			}
			$info['exts'][0]['key'] = $info_title1[$cids[0]];
			$business_type = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['business_type'])))),'title');
			$title = array();
			foreach($business_type as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][0]['value'] = $title ? implode(',',$title) : '';
			unset($title);
			$info['exts'][1]['key'] = $info_title1[$cids[1]];
			$interested = $CI->mcategory->get_all(array('in'=>array('id',array_values(explode(',',$info['interested'])))),'title');
			$title = array();
			foreach($interested as $row) {
				$title[] = $row['title'];
			}
			$info['exts'][1]['value'] = isset($title) ? implode(',',$title) : '';
			break;
	}
	//var_dump($info);die();
	return $info;

}
if (!function_exists('ordernum_time')) {
	// 生成订单时用
	// @param $insert  插入内容
	function ordernum_time($insert='', $noline=false)
	{
		$base = date('ymdHis', time());
		if ($insert) {
			return $base.$insert.nanoSecond();
		} else {
			if ($noline) {
				return $base.nanoSecond();
			} else {
				return $base.'-'.nanoSecond();
			}
		}
	}
}

if (!function_exists('get_order_sn')) {
    // 生成订单时用
    //$table  表名 例如boc_needs
    //S悬赏需求(boc_needs)\E差价订单(boc_need_order)\L长文章赞赏(boc_long_article)\C充值(boc_pay_logs)
    function get_order_sn($table,$letter='S')
    {
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
        $dt = date('Ymdhis');
        $order_sn = $letter .'-'. $dt . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        if($letter=='S'){
            $order = $this->db->query("select order_sn from $table where order_sn=$order_sn")->result_array();
        }else{
            $order = $this->db->query("select pay_code from $table where pay_code=$order_sn")->result_array();
        }
        if (empty($order)) {
            return $order_sn;
        }
        /* 如果有重复的，则重新生成 */
        return $this->get_order_sn();
    }
}
/**
 * @param $title 文件说明 string
 * @param $head excel 'A,B,C....'  string
 * @param $body 传入的data数据 array
 */
//导出excel
function export_excel($title,$head,$body) {
	include LIBS_PATH.'libraries/MExcel.php';
	$excel = new MExcel();
	$excel->getActiveSheet()->setTitle($title);
	$excel->configHead($head);
	$excel->configBody($body);
	ob_end_clean();//清除缓冲区,避免乱码
	header('Pragma:public');
	header('Content-Type:application/vnd.ms-excel;charset=utf-8');
	header('Content-Disposition:attachment;filename="'.$title.'(' . date('Ymd-His') . ').xls"');
	header('Content-Disposition:inline;filename="'.$title.'(' . date('Ymd-His') . ').xls"');
	$objWriter = new MExcel_Writer($excel);
	$objWriter->save_ext();
	return ;
}
//导入excel
/**
 * @param $data
 * @param bool|false $cell
 * @param string $type
 * @return array 传 row 表示返回的单列的值 ; 传column 表示返回每列的值(即读取全部)
 * @throws Exception
 */
function import_excel($data,$cell=false,$type='row') {
	$import_data = array();
	$_cells = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
	include LIBS_PATH.'libraries/PHPExcel.php';
	include LIBS_PATH.'libraries/PHPExcel/IOFactory.php';
	include LIBS_PATH.'libraries/PHPExcel/Reader/Excel5.php';
	$filename=$data['file_excel']['tmp_name'];//指定excel文件
	//以上三步加载phpExcel的类
	$objReader = PHPExcel_IOFactory::createReaderForFile($filename);//use excel2007 for 2007 format
	$objReader->setReadDataOnly(true);
	$objPHPExcel = $objReader->load($filename); //$filename可以是上传的文件，或者是指定的文件
	$sheet = $objPHPExcel->getSheet(0);//
	$highestRow = $sheet->getHighestRow(); // 取得总行数
	$highestColumn = $sheet->getHighestColumn(); // 取得总列数
	$cell = $cell ?  explode(',',$cell) : $_cells;
	if($type == 'row') {
		for($j=1;$j<=$highestRow;$j++)
		{
			for($i = 0;$i<count($cell);$i++) {
				$val = $objPHPExcel->getActiveSheet()->getCell($cell[$i].$j)->getValue();//获取最后一列的值
				$import_data[$j][] = $val ? $val : '';
			}
		}
	} else {
		for($i = 1;$i<=$highestRow;$i++) {
			for($j='A';$j<=$highestColumn;$j++)
			{
				$val = $objPHPExcel->getActiveSheet()->getCell($j.$i)->getValue();//获取最后一列的值
				$import_data[$i.$j] = $val ? $val : '';
			}
		}

	}
	return $import_data;
}
function goto_message($message,$uri=-1,$toSiteUrl=true){
	$message=addslashes($message);
	if(is_int($uri))$uri='history.go('.$uri.');';
	else if($toSiteUrl)$uri='location.href="'.site_url($uri).'";';
	header("Content-type:text/html;Charset=utf-8");
	exit('<script>alert("'.$message.'");'.$uri.'</script>');
}
if (!function_exists('genToken')) {
	// 生成用户token
	/**
	 * @param len长度
	 */
	function genToken($len=64)
	{
		$CI =& get_instance();
		if (!isset($CI->maccount_token)) {
			$CI->load->model('account_token_model', 'maccount_token');
		}
		$token = rand_str($len);

		$tmp = $CI->maccount_token->get_one(array('token'=>$token));

		do {
			$token = rand_str($len);
			$tmp = $CI->maccount_token->get_one(array('token'=>$token));
		} while (!empty($tmp));

		return $token;
	}
}

